package com.example.mybatis.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;


@Service
@RequiredArgsConstructor
public class RedisService {


    private final RedisTemplate<String, Object> redisTemplate;
    private Integer expireTime=60;

    public void setValue(String key, Object value) {

        redisTemplate.opsForValue().set(key, value);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void deleteKey(String key) {
        redisTemplate.delete(key);
    }

    public void setHashValue(String key, String hashKey, Object value) {
        redisTemplate.opsForHash().put(key, hashKey, value);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }

    public Object getHashValue(String key, String hashKey) {
        return redisTemplate.opsForHash().get(key, hashKey);
    }

    public void deleteHashKey(String key, String hashKey) {
        redisTemplate.opsForHash().delete(key, hashKey);
    }

    public <T> void setPaginatedList(String keyPrefix, int currentPage, int pageSize, IPage<T> page) {
        String key = String.format("%s:%d:%d", keyPrefix, currentPage, pageSize);
        // 将数据缓存到 Redis 中，设置过期时间为 1 分钟
        redisTemplate.opsForValue().set(key, page);
        redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
    }
    public <T> IPage<T> getPaginatedList(String keyPrefix, int currentPage, int pageSize, Supplier<IPage<T>> dataSupplier) {
        String key = String.format("%s:%d:%d", keyPrefix, currentPage, pageSize);

        // 尝试从 Redis 中获取分页数据
        IPage<T> page = (IPage<T>) redisTemplate.opsForValue().get(key);

        if (page == null) {
            // 如果 Redis 中没有数据，从数据库中获取
            page = dataSupplier.get();

            // 将数据缓存到 Redis 中
            redisTemplate.opsForValue().set(key, page);
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
        }
        return page;
    }

}
